const { Controller } = require('egg')
const dayjs = require('dayjs')
const village = require('../../data/village')
const { build } = require('node-xlsx')

class ApiController extends Controller {
  /**
   * @api {get} /district/scan [地区] 扫码数据
   * @apiGroup District
   * @apiDescription 场所码管理-全县近期扫码人数趋势
   * 
   * @apiParam {String} [scope=day] 范围 day（天）、week（周）、month（月）
   * 
   * @apiSuccessExample {json} Success-Response:
  {
      "code": 0,
      "msg": "success",
      "data": [
          {
              "label": "2022-12-07",
              "value": 34
          }
      ]
  }
   */
  async scan() {
    const { ctx } = this
    const { query } = ctx
    const scope = query.scope || 'day'

    const returnData = await ctx.model.TrackData.find({ trackName: `${scope}_scan` })
      .limit(7)
      .then(res => {
        return res.map(item => {
          let label

          if (scope == 'month') {
            label = dayjs(item.trackDate).format('YYYY-MM')
          } else {
            label = dayjs(item.trackDate).format('YYYY-MM-DD')
          }

          return {
            label,
            value: item.total,
          }
        })
      })

    ctx.body = {
      code: 0,
      msg: 'success',
      data: returnData,
    }
  }

  /**
   * @api {get} /district/stat [地区] 统计数据
   * @apiGroup District
   * @apiDescription 乡镇名称和村名二选一
   * 
   * @apiParam {String} [townName] 镇名称
   * @apiParam {String} [villageName] 村名
   * 
   * @apiSuccessExample {json} Success-Response:
{
    "code": 0,
    "msg": "success",
    "data": {
        "czTotal": 1, // 常住人口
        "fczTotal": 1, // 非常住
        "placeTotal": 2, // 场所数量
        "scanTotal": 0, // 扫码次数
        "fxrs": 0, // 返乡人数
        "tsrq": 0, // 特殊人群
        "zdry": 0, // 31类重点人员
        "yxry": 0, // 阳性人员
        "hsTotal": 0, // 核酸数量
        "hsPercent": 0, // 核酸采样百分比

        // 下属行政区，镇才有
        "children": [
            "东门村民委员会",
            "南门村民委员会",
        ]
    }
}
   */
  async stat() {
    const { ctx } = this
    const { knex } = this.app
    const { query } = ctx
    const {
      TABLE_PERSON,
      TABLE_PLACE_CODE,
      TABLE_SCAN_RECORD,
      TABLE_POSITIVE,
      TABLE_PERSON_BACK_HOME,
      TABLE_HS_RESULT,
    } = this.config.constant

    if (!query.townName && !query.villageName) throw '缺少参数'
    const type = query.townName ? 'town' : 'village'

    const returnData = {
      czTotal: 0,
      fczTotal: 0,
      placeTotal: 0, // 场所数量
      scanTotal: 0, // 扫码总数

      fxrs: 0, // 返乡人数
      tsrq: 0, // 特殊人群
      zdry: 0, // 31类重点人员
      yxry: 0, // 阳性人员

      hsTotal: 0, // 核酸数量
      hsPercent: 0, // 核酸采样百分比

      // 下属节点
      children: [],
    }

    await Promise.all([
      (async () => {
        if (type == 'town') {
          const area = await knex('sys_area_code')
            .where(builder => {
              builder.where('title', query.townName)
              builder.where('GRADE', 4)
            })
            .then(res => res[0])

          if (area) {
            returnData.children = await knex('sys_area_code')
              .where({
                PARENT_CODE: area.CODE,
              })
              .then(res => {
                return res.map(item => {
                  return item.title
                })
              })
          }
        }
      })(),

      // 获取常住/非常住人口
      knex(TABLE_PERSON)
        .select(
          knex.raw([
            `count(sfczrq = '是' or null) AS cz`,
            `count(sfczrq = '否' or null) AS fcz`,
            `count(sfzdry = '是' or null) AS zdry`,
          ])
        )
        .where(type == 'town' ? 'areajd' : 'areajwh', type == 'town' ? query.townName : query.villageName)
        .then(res => {
          res.map(item => {
            returnData.czTotal += item.cz
            returnData.fczTotal += item.fcz
            returnData.zdry += item.zdry
          })
        }),

      // 场所数量
      knex(TABLE_PLACE_CODE)
        .where(
          type == 'town' ? 'unit_areajd' : 'unit_areajwh',
          type == 'town' ? query.townName : query.villageName
        )
        .count()
        .then(res => {
          returnData.placeTotal = res[0]['count(*)']
        }),

      // 扫码总数
      knex(TABLE_SCAN_RECORD)
        .where(type == 'town' ? 'areajd' : 'area', type == 'town' ? query.townName : query.villageName)
        .count()
        .then(res => {
          returnData.scanTotal = res[0]['count(*)']
        }),

      // 阳性人员
      knex(TABLE_POSITIVE)
        .where(type == 'town' ? 'areajd' : 'area', type == 'town' ? query.townName : query.villageName)
        .count()
        .then(res => {
          returnData.yxry = res[0]['count(*)']
        }),

      // 返乡人数 TODO 有问题
      // knex(TABLE_PERSON_BACK_HOME)
      //   .where(type == 'town' ? 'areajd' : 'area', type == 'town' ? query.townName : query.villageName)
      //   .count()
      //   .then(res => {
      //     returnData.fxrs = res[0]['count(*)']
      //   }),

      // 核酸数量 TODO 数据只到区
      // knex(TABLE_HS_RESULT)
      //   .where(type == 'town' ? 'areajd' : 'area', type == 'town' ? query.townName : query.villageName)
      //   .count()
      //   .then(res => {
      //     returnData.hsTotal = res[0]['count(*)']
      //   }),
    ])

    ctx.body = {
      code: 0,
      msg: 'success',
      data: returnData,
    }
  }

  /**
   * @api {get} /district/village [地区] 村列表
   * @apiGroup District
   * 
   * @apiSuccessExample {json} Success-Response:
  {
      "code": 0,
      "msg": "success",
      "data": [
        {
            // 村名
            "villageName": "周庄居民委员会",

            // 经纬度
            "lnglat": [
                114.567154457745,
                33.7638189932144
            ]
        },
  }
   */
  async village() {
    const { ctx } = this
    const { query } = ctx

    ctx.body = {
      code: 0,
      msg: 'success',
      data: village,
    }
  }
}

module.exports = ApiController
